<template>
  <div>
    <el-form :model="queryData" inline>
      <el-form-item>
        <el-date-picker v-model="queryData.createTime"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.id" placeholder="园区ID" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.gardenName" placeholder="园区名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.customerName" placeholder="姓名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.customerMobile" placeholder="手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.orderNo" placeholder="工单号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryData.rulesId" placeholder="分佣规则" style="width: 100%" clearable filterable>
          <el-option :label="item.rulesName" :value="item.id" v-for="(item,index) in rulesList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryData.isConfirm" placeholder="佣金发放" clearable>
          <el-option label="未发放" value="0"></el-option>
          <el-option label="已发放" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryData.orderStatus" placeholder="支付状态" clearable>
          <el-option label="未支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryData.payId" placeholder="流水号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getInfoRequest">查 询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="tableLoading" :data="tableData">
      <el-table-column label="工单创建日期" align="center" prop="createTime" width="140px"/>
      <el-table-column label="园区ID" align="center" prop="id" width="80px"/>
      <el-table-column label="园区名称" align="center" prop="gardenName" width="140px"/>
      <el-table-column label="姓名" align="center" prop="customerName"/>
      <el-table-column label="手机号" align="center" prop="customerMobile" width="140px"/>
      <el-table-column label="工单号" align="center" prop="orderNo" width="150px"/>
      <el-table-column label="订单状态" align="center" prop="orderStatus"/>
      <el-table-column label="订单金额" align="center" prop="orderPrice"/>
      <el-table-column label="佣金总计" align="center" prop="commission"/>
      <el-table-column label="分佣规则" align="center" prop="rulesName" width="140px"/>
      <el-table-column label="租赁日期" align="center" prop="leaseTime" width="140px"/>
      <el-table-column label="面积" align="center" prop="area"/>
      <el-table-column label="租赁单价" align="center" prop="unitPrice"/>
      <el-table-column label="月租金" align="center" prop="monthPrice"/>
      <el-table-column label="合同" align="center">
        <template slot-scope="{row, $index}">
          <el-button type="text" @click="imageArrEvent(row)">{{row.contract ? '查看' : '未上传'}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="orderStatus"/>
      <el-table-column label="流水号" align="center" prop="payId" width="210px"/>
      <el-table-column label="操作" align="center" prop="createTime" fixed="right" width="150px">
        <template slot-scope="{row, $index}">
          <el-button type="text" @click="editEvent(row)">编辑</el-button>
          <el-button type="text" @click="getPostAppletWorkOrderComPayment(row.id)" v-if="row.payId && row.isConfirm == 0">发放佣金</el-button>
          <el-button type="text" v-if="row.payId  && row.isConfirm == 1">已放佣金</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="queryData.total" :page.sync="queryData.pageNum" :limit.sync="queryData.pageSize"
                @pagination="getRequestList()"/>
    <el-drawer title="修改工单" :visible.sync="drawer" direction="rtl" size="500px" :before-close="formClose"
               destroy-on-close custom-class="drawer-custom">
      <el-form :model="formData" :rules="formRules" ref="form-data" label-position="top" class="form-data">
        <el-form-item label="佣金总计" prop="orderPrice">
          <el-input v-model="formData.commission" type="number" placeholder="请输入佣金总计">
            <div slot="suffix" class="row-div" style="height: 100%;padding: 0 5px">元</div>
          </el-input>
        </el-form-item>
        <el-form-item label="订单金额" prop="orderPrice">
          <el-input v-model="formData.orderPrice" type="number" placeholder="请输入佣金总计">
            <div slot="suffix" class="row-div" style="height: 100%;padding: 0 5px">元</div>
          </el-input>
        </el-form-item>
        <el-form-item label="分佣规则" prop="leaseTime">
          <el-select v-model="formData.rulesId" placeholder="请选择分佣规则" style="width: 100%" filterable>
            <el-option :label="item.rulesName" :value="item.id" v-for="(item,index) in rulesList" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="租赁日期" prop="leaseTime">
          <el-date-picker v-model="formData.leaseTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择租赁日期" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="formData.area" type="number" placeholder="请输入房产面积">
            <div slot="suffix" class="row-div" style="height: 100%;padding: 0 5px">㎡</div>
          </el-input>
        </el-form-item>
        <el-form-item label="租赁单价" prop="unitPrice">
          <el-input v-model="formData.unitPrice" type="number" placeholder="请输入租赁单价">
            <div slot="suffix" class="row-div" style="height: 100%;padding: 0 5px">元/㎡·天</div>
          </el-input>
        </el-form-item>
        <el-form-item label="月租金" prop="monthPrice">
          <el-input v-model="formData.monthPrice" type="number" placeholder="请输入月租金">
            <div slot="suffix" class="row-div" style="height: 100%;padding: 0 5px">元</div>
          </el-input>
        </el-form-item>
        <el-form-item label="合同" prop="contract">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadFileHeader"
            list-type="picture-card"
            :limit="6"
            :file-list="formData.contract"
            :on-remove="uploadRemove"
            :on-success="uploadChange">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item class="form-but-view">
          <el-button class="but-view" type="primary" @click="submit">提 交</el-button>
          <el-button class="but-view" @click="formClose">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <div v-if="imageArr.length" style="position: absolute; left: -3000px">
      <el-image :src="imageArr[0]" :preview-src-list="imageArr" ref="imageArr"/>
    </div>
  </div>
</template>

<script>
  import {
    getAppletWorkOrderList,
    postAppletWorkOrderEdit,
    postAppletWorkOrderComPayment,
    getAppletRulesList
  } from "@/api/eh-api";
  import {getToken} from "@/utils/auth";

  export default {
    name: "order",
    data() {
      return {
        imageArr: [],
        uploadUrl: '',
        uploadFile: '',
        uploadFileHeader: null,
        rulesList: [], // 规则列表
        tableData: [],
        tableLoading: false,
        drawer: false,
        detailDrawer: false,
        detail: {},
        queryData: {
          id: null,
          payId: null,
          createTime: null,
          gardenName: null,
          customerName: null,
          customerMobile: null,
          orderNo: null,
          rulesId: null,
          total: 0,
          pageNum: 1,
          pageSize: 10,
        },
        formData: {
          area: null, // 面积
          contract: [], // 合同
          leaseTime: null, // 租赁日期
          monthPrice: null, // 月租金
          orderPrice: null, // 订单总计
          commission: null, // 佣金总计
          unitPrice: null, // 租赁单价
          rulesId: null, // 分佣规则ID
          rulesName: null, // 分佣规则名称
        },
        formRules: {
          area: [
            {required: true, message: '请输入房产面积', trigger: 'blur'},
          ],
          monthPrice: [
            {required: true, message: '请输入月租金', trigger: 'blur'},
          ],
          unitPrice: [
            {required: true, message: '请输入租赁单价', trigger: 'blur'},
          ],
          orderPrice: [
            {required: true, message: '请输入佣金总计', trigger: 'blur'},
          ],
          contract: [
            {required: true, message: '请输入合同内容', trigger: 'blur'},
          ],
          leaseTime: [
            {required: true, message: '请选择租赁日期', trigger: 'blur'},
          ],
          rulesId: [
            {required: true, message: '请选择分佣规则', trigger: 'blur'},
          ]
        }
      }
    },
    beforeMount() {
      this.uploadUrl = process.env.VUE_APP_BASE_API + '/wx/appletFeedback/uploadimg'
      this.uploadFile = process.env.VUE_APP_BASE_API + '/common/uploadFile2Cos'
      this.uploadFileHeader = {Authorization: "Bearer " + getToken()}
      this.getInfoRequest()
    },
    methods: {
      imageArrEvent ({contract}) {
        if (!contract) return this.$message.warning('请上传合同书')
        this.tableLoading = true;
        const arr = contract.split(',')
        this.imageArr = arr
        setTimeout(() => {
          const ref = this.$refs['imageArr']
          ref.$el.firstChild.click()
          this.tableLoading = false;
        }, 1000)
      },
      editEvent(row) {
        const formData = JSON.parse(JSON.stringify(row))
        const fileList = formData.contract ? formData.contract.split(',') : []
        formData.contract = fileList.map((item, index) => {
          return {
            url: item,
            uid: Date.now() + (index + 1)
          }
        })
        this.formData = formData
        this.drawer = true
      },
      /**
       *  删除文件事件
       */
      uploadRemove(e, fileList) {
        this.formData.contract = fileList
      },
      /**
       *  上传文件成功事件
       */
      uploadChange(file) {
        console.log(file)
        this.formData.contract.push(file.data)
      },
      /**
       * 修改看房工单请求
       */
      submit() {
        this.$refs['form-data'].validate(async (valid) => {
          if (!valid) return this.$message.warning('请将内容填写完整!');
          const formData = JSON.parse(JSON.stringify(this.formData));
          const fileList = this.formData.contract.map(item => item.url);
          const rules = this.rulesList.find(item => item.id == formData.rulesId)
          formData.rulesName = rules.rulesName
          formData.contract = fileList.join(',');
          await postAppletWorkOrderEdit(formData);
          this.$message.success('操作成功!')
          this.formClose()
          this.getRequestList()
        });
      },
      /**
       * 取消抽屉 并情况form 表单
       */
      formClose() {
        this.$refs['form-data'].resetFields(this.formData)
        this.drawer = false
        this.detailDrawer = false
      },
      /**
       * 发放佣金请求
       */
      getPostAppletWorkOrderComPayment(id) {
        this.$confirm('此操作无法修改, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await postAppletWorkOrderComPayment({id})
          this.$message.success('操作成功!')
          this.formClose()
          this.getRequestList()
        })
      },
      /**
       * 初始化请求
       */
      getInfoRequest() {
        this.queryData.pageNum = 1;
        this.tableData = [];
        this.getRequestList()
        this.getAppletRulesList()
      },
      async getAppletRulesList() {
        const res = await getAppletRulesList({sign: '1'})
        this.rulesList = res.rows;
      },
      /**
       * 获取数据列表
       * @returns {Promise<ElMessageComponent>}
       */
      async getRequestList() {
        this.tableLoading = true;
        const formData = JSON.parse(JSON.stringify(this.queryData))
        if (formData.createTime && formData.createTime.length > 1) {
          formData.gmtStart = formData.createTime.shift()
          formData.gmtEnd = formData.createTime.pop()
        }
        delete formData.createTime
        const res = await getAppletWorkOrderList(formData).finally(() => this.tableLoading = false)
        if (res.code != 200) return this.$message.warning(res.mag)
        this.tableData = res.rows;
        this.queryData.total = res.total - 0
      }
    }
  }
</script>

<style scoped>
</style>
